#include "tcpclient.h"
#include <QDebug>

TcpClient::TcpClient(QObject *parent) : QObject(parent)
{
    m_socket = new QTcpSocket(this);

    // 连接“数据可读”和“状态变化”信号到对应槽函数
    connect(m_socket, &QTcpSocket::readyRead, this, &TcpClient::slotReadyRead);
    connect(m_socket, &QTcpSocket::stateChanged, this, &TcpClient::slotStateChanged);
}

TcpClient::~TcpClient()
{
    disconnectFromServer();
}

bool TcpClient::connectToServer(const QString &host, quint16 port)
{
    m_socket->connectToHost(host, port);
    // 等待连接（超时3秒）
    return m_socket->waitForConnected(3000);
}

void TcpClient::sendData(const QByteArray &data)
{
    if (m_socket->state() == QTcpSocket::ConnectedState) {
        m_socket->write(data);
        qDebug() << "Sent to server: " << data;
    } else {
        qDebug() << "Not connected to server, can't send data.";
    }
}

void TcpClient::disconnectFromServer()
{
    m_socket->disconnectFromHost();
    if (m_socket->state() != QTcpSocket::UnconnectedState) {
        m_socket->waitForDisconnected(3000);
    }
}

void TcpClient::slotReadyRead()
{
    if (m_socket->bytesAvailable() > 0) {
        // 读取服务器数据
        QByteArray data = m_socket->readAll();
        emit signalNewData(data);
        qDebug() << "Received from server: " << data;
    }
}

void TcpClient::slotStateChanged(QAbstractSocket::SocketState state)
{
    bool isConnected = (state == QTcpSocket::ConnectedState);
    emit signalConnectionStatus(isConnected);
    qDebug() << "Connection state changed: " << (isConnected ? "Connected" : "Disconnected");
}
